import { defineStore } from "pinia";
import { asyncRouterMap, constantRouterMap } from "@/router";
import { flatMultiLevelRoutes, promoteRoute } from "@/utils/routerHelper";
import { store } from "../index";
import { cloneDeep } from "lodash-es";
import { getMenu } from "@/api/menu";
import storage from "@/utils/storage";
export interface PermissionState {
  routers: AppRouteRecordRaw[];
  addRouters: AppRouteRecordRaw[];
  isAddRouters: boolean;
  menuTabRouters: AppRouteRecordRaw[];
  iscache: boolean;
}

export const usePermissionStore = defineStore("permission", {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    isAddRouters: false,
    menuTabRouters: [],
    iscache: storage.get("iscache", false) == "0" ? false : true,
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers;
    },
    getAddRouters(): AppRouteRecordRaw[] {
      console.log(flatMultiLevelRoutes(cloneDeep(this.addRouters)));
      return flatMultiLevelRoutes(cloneDeep(this.addRouters));
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters;
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters;
    },
  },
  actions: {
    toggleCache() {
      const status = this.iscache ? "0" : "1";
      storage.set("iscache", status);
      this.iscache = !this.iscache;
    },
    getRouter() {
      return new Promise<void>((resolve) => {
        getMenu().then((res) => {

          console.log(res.data);
          let routerMap: AppRouteRecordRaw[] = [];
          routerMap = promoteRoute(res.data);
          this.addRouters = routerMap.concat([
            {
              path: "/:path(.*)*",
              redirect: "/404",
              name: "NoFind",
              meta: {
                hidden: true,
                breadcrumb: false,
              },
            },
          ]);
          this.routers = cloneDeep(constantRouterMap).concat(routerMap);
          console.log(this.routers);
          resolve();
        });
      });
    },
    generateRoutes(): Promise<unknown> {
      return new Promise<void>((resolve) => {
        let routerMap: AppRouteRecordRaw[] = [];
        // 直接读取静态路由表
        routerMap = cloneDeep(asyncRouterMap);

        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          {
            path: "/:path(.*)*",
            redirect: "/404",
            name: "404Page",
            meta: {
              hidden: true,
              breadcrumb: false,
            },
          },
        ]);

        // 渲染菜单的所有路由
        this.routers = cloneDeep(constantRouterMap).concat(routerMap);

        resolve();
      });
    },
    setIsAddRouters(state: boolean): void {
      this.isAddRouters = state;
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers;
    },
  },
});

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store);
};
